﻿using Minio;
using Minio.Exceptions;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace Coldairarrow.Util.Helper
{
    /*
     * 开发人：崔楠
     * 提交日期：2022-02-18 15:08
     * 修改内容：编写minio操作类
     * 上传SVN：否
     */
    /// <summary>
    /// 插入minio
    /// </summary>
    public class MinioHelper
    {
        /// <summary>
        /// 定义MinIO客户端对象
        /// </summary>
        private MinioClient minio = new MinioClient("120.46.133.253:9000", "minioadmin", "q1w2e3r4t5!@#$%");


        #region 上传文件至minio
        /// <summary>
        /// 上传文件到MinIO
        /// </summary>
        /// <param name="bucketName"></param>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public async Task<string> UploadFile(string bucketName, string filePath)
        {
            return await Task.Run(async () =>
            {
                var retMsg = string.Empty;

                try
                {
                    //上传到MinIO中的文件名称 D:\Code\shengzhuo-svn\Coldairarrow.Api\wwwroot\Upload\男头像.png
                    var objName = filePath.Substring(filePath.LastIndexOf('\\') + 1, filePath.Length - filePath.LastIndexOf('\\') - 1);
                    //var objName = Guid.NewGuid().ToString("N") + filePath.Substring(filePath.LastIndexOf('.'), filePath.Length - filePath.LastIndexOf('.'));
                    //检查是否存在桶
                    bool existBucket = await minio.BucketExistsAsync(bucketName);
                    if (!existBucket)
                    {
                        //创建桶
                        await minio.MakeBucketAsync(bucketName);

                        //设置桶的访问权限（读、写、读和写）
                        await SetPolicyAsync(bucketName, 1);
                    }

                    //上传文件到桶中
                    await minio.PutObjectAsync(bucketName, objName, filePath);

                   // retMsg = "http://119.3.210.33:8806/xunjian/" + objName;
                    retMsg = "http://120.46.133.253:9000/shengzhuo/" + objName;
                }
                catch (MinioException e)
                {
                    retMsg = "文件上传错误：" + e.Message;
                }

                return retMsg;
            });
        }
        #endregion

        #region 设置桶的访问策略
        /// <summary>
        /// 设置桶的访问策略（读、写、读和写）
        /// </summary>
        /// <param name="bucketName"></param>
        /// <param name="policyType"></param>
        /// <returns></returns>
        private async Task SetPolicyAsync(string bucketName, int policyType = 1)
        {
            //设置桶的访问权限（读、写、读和写）
            var policyRead = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:GetBucketLocation\"],\"Resource\":[\"arn:aws:s3:::BUCKETNAME\"]},{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:ListBucket\"],\"Resource\":[\"arn:aws:s3:::BUCKETNAME\"],\"Condition\":{\"StringEquals\":{\"s3:prefix\":[\"BUCKETPREFIX\"]}}},{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:GetObject\"],\"Resource\":[\"arn:aws:s3:::BUCKETNAME/BUCKETPREFIX*\"]}]}";
            var policyWrite = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:GetBucketLocation\",\"s3:ListBucketMultipartUploads\"],\"Resource\":[\"arn:aws:s3:::BUCKETNAME\"]},{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:AbortMultipartUpload\",\"s3:DeleteObject\",\"s3:ListMultipartUploadParts\",\"s3:PutObject\"],\"Resource\":[\"arn:aws:s3:::BUCKETNAME/BUCKETPREFIX*\"]}]}";
            var policyReadWrite = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:GetBucketLocation\",\"s3:ListBucketMultipartUploads\"],\"Resource\":[\"arn:aws:s3:::BUCKETNAME\"]},{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:ListBucket\"],\"Resource\":[\"arn:aws:s3:::BUCKETNAME\"],\"Condition\":{\"StringEquals\":{\"s3:prefix\":[\"BUCKETPREFIX\"]}}},{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:PutObject\",\"s3:AbortMultipartUpload\",\"s3:DeleteObject\",\"s3:GetObject\",\"s3:ListMultipartUploadParts\"],\"Resource\":[\"arn:aws:s3:::BUCKETNAME/BUCKETPREFIX*\"]}]}";

            var policySet = policyType == 1 ? policyRead :
               policyType == 2 ? policyWrite : policyReadWrite;

            await minio.SetPolicyAsync(bucketName, policySet.Replace("BUCKETNAME", bucketName).Replace("BUCKETPREFIX", "*.*"));
        }
        #endregion
    }
}
